package ve.com.wayoyo.wuml_case.Bluetooth;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

public class ThreadServer extends Thread {
	private final BluetoothServerSocket mmServerSocket;
	private String _nameDiagram;
	private Handler _mHandler;

	public ThreadServer(Handler mHandler) {
		
		this._mHandler = mHandler;
		
		// Use a temporary object that is later assigned to mmServerSocket,
		// because mmServerSocket is final
		BluetoothServerSocket tmp = null;
		try {
			BluetoothAdapter mBluetoothAdapter = BluetoothAdapter
					.getDefaultAdapter();
			UUID mY_UUIDUuid = UUID
					.fromString("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa");
			// MY_UUID is the app's UUID string, also used by the client code
			tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("wuml",
					mY_UUIDUuid);
		} catch (IOException e) {
		}
		mmServerSocket = tmp;
	}

	public void run() {
		BluetoothSocket socket = null;
		// Keep listening until exception occurs or a socket is returned
		while (true) {
			try {
				socket = mmServerSocket.accept();
			} catch (IOException e) {
				break;
			}
			// If a connection was accepted
			if (socket != null) {
				// Do work to manage the connection (in a separate thread)
				manageConnectedSocket(socket);
				try {
					mmServerSocket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;
			}
		}
	}

	private void manageConnectedSocket(BluetoothSocket socket) {
		InputStream tmpIn = null;
		OutputStream tmpOut = null;
		FileOutputStream fos = null;
		boolean flagEnviar = false;
		boolean flagNombre = true;
		// Get the input and output streams, using temp objects because
		// member streams are final
		byte[] buffer = new byte[1024]; // buffer store for the stream
		int bytes; // bytes returned from read()
		try {			
			tmpIn = socket.getInputStream();
			tmpOut = socket.getOutputStream();
		} catch (IOException e) {
		}
		// Keep listening to the InputStream until an exception occurs
		String archivo = "";
		while (true) {
			try {
				if (flagEnviar) {
					byte[] bufferOut = "Ok".getBytes();
					tmpOut.write(bufferOut);
					tmpOut.flush();
					flagEnviar = false;
				} else {
					// Read from the InputStream
					bytes = tmpIn.read(buffer);
					String aux = new String(buffer);
					if (!aux.contains("EOF")) {//						
							if (flagNombre){
								String line = aux.split("\n")[0]+"\n";								
								_nameDiagram = line.substring(line.indexOf("\"")+1,line.indexOf("\"")+
										             line.substring(line.indexOf("\"")+1).indexOf("\"")+1);
								
								File folder_dest = new File(
										Environment.getExternalStorageDirectory()
										+ "/WUML/DiagramasBluetooth/DIAGRAMAS");
								if (!folder_dest.exists()) {									
									try {
										folder_dest.mkdirs();
									} catch (Exception e) {
									}
								}
								fos = new FileOutputStream(getRutaValida());							
								fos.write(line.getBytes());
								flagNombre = false;
							}else{
								fos.write((aux.split("\n")[0]+"\n").getBytes());
							}

						buffer = new byte[1024];
						flagEnviar = true;
					} else {
						fos.flush();
						fos.close();						
						fos = null;
						Message msg = new Message();
						Bundle data = new Bundle();
						data.putString(null, "Recibido el diagrama:"+_nameDiagram);
						msg.setData(data);
						_mHandler.sendMessage(msg);
						break;
					}
				}
			} catch (IOException e) {
				break;
			}
		}
		System.out.println(archivo);

	}

	private File getRutaValida() {
		int i =1;
		File retFile = new File(Environment.getExternalStorageDirectory()
				+ "/WUML/DiagramasBluetooth/DIAGRAMAS/"+_nameDiagram+".wuml");
		while (true){			
			if (retFile.exists()){
				retFile = new File(Environment.getExternalStorageDirectory()
						+ "/WUML/DiagramasBluetooth/DIAGRAMAS/"+_nameDiagram+"("+i+").wuml");
				i++;
			}else
				break;
		}	
		_nameDiagram = _nameDiagram+"("+i+")";
		return retFile;
	}

	/** Will cancel the listening socket, and cause the thread to finish */
	public void cancel() {
		try {
			mmServerSocket.close();
		} catch (IOException e) {
		}
	}
}